import { useChatStore } from "@/store/useChatStore";

export type WSOptions = {
  url: string;
  sessionId?: string;
  token?: string; // 可选：鉴权用
  onOpen?: () => void;
  onMessage?: (data: any) => void;
  onClose?: () => void;
  onError?: (err: Event) => void;
  reconnect?: boolean; // 是否自动重连
  reconnectInterval?: number; // 重连间隔(ms)
  binaryType?: BinaryType; // 二进制数据类型
};

export class WSClient {
  private ws: WebSocket | null = null;
  private options: WSOptions;
  private reconnectTimer: any = null;

  constructor(options: WSOptions) {
    this.options = { reconnect: true, reconnectInterval: 3000, ...options };
    this.connect();
  }

  private connect() {
    const { url, sessionId, token, binaryType } = this.options;
    const wsUrl = token
      ? `${url}?sessionId=${sessionId}&Authorization=${token}`
      : url;

    this.ws = new WebSocket(wsUrl);
    this.ws.binaryType = binaryType || "arraybuffer";

    this.ws.onopen = () => {
      console.log("✅ WebSocket 已连接");
      this.options.onOpen?.();
    };

    this.ws.onmessage = (event) => {
      try {
        let content = "";
        const data = JSON.parse(event.data);
        this.options.onMessage?.(data);
        content += data.data;
        console.log("收到 AI 回复:", data, content);
        useChatStore.getState().addChunkMessage(data.data);
      } catch {
        this.options.onMessage?.(event.data);
      }
    };

    this.ws.onerror = (err) => {
      console.error("❌ WebSocket 错误:", err);
      this.options.onError?.(err);
    };

    this.ws.onclose = () => {
      console.log("🔌 WebSocket 已关闭");
      this.options.onClose?.();

      if (this.options.reconnect) {
        this.reconnectTimer = setTimeout(() => {
          console.log("♻️ WebSocket 正在重连...");
          this.connect();
        }, this.options.reconnectInterval);
      }
    };
  }

  send(data: any) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      if (typeof data === "string") {
        this.ws.send(data);
      } else if (data instanceof ArrayBuffer || data instanceof Blob) {
        console.log("📤 发送二进制数据:", data);
        this.ws.send(data);
      } else {
        this.ws.send(JSON.stringify(data));
      }
    } else {
      console.warn("⚠️ WebSocket 未连接，无法发送");
    }
  }

  sendAudio(chunk: ArrayBuffer | Blob) {
    this.send(chunk);
  }

  close() {
    if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
    this.options.reconnect = false;
    this.ws?.close();
  }
}
